<?php
if (get_magic_quotes_gpc()) {
    function magicQuotes_awStripslashes(&$value, $key) {$value = stripslashes($value);}
    $gpc = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    array_walk_recursive($gpc, 'magicQuotes_awStripslashes');
}

require '../lib/facebook.php';

// http://fql-builder.mariogarcia.biz/
$facebook = new Facebook(array(
  'appId'  => 'yourAppId',
  'secret' => 'yourAppSecret',
));

// Get User ID
$user = $facebook->getUser();

if($_GET['code'] && $_GET['state']){
    header('Location: ../');
    exit;
}

if(!$user){
  $loginUrl = $facebook->getLoginUrl();
  echo "<a href='$loginUrl'>Log In</a>"; 
  exit;   
}

$logout = $facebook->getLogoutUrl();
if($user){
    $params['method']='fql.query';
    $params['query']=$_POST['query'];

    //Run Query
    try {
	$result = $facebook->api($params);
    $out = print_r($result,true);
    echo "
    <a href='#' onclick='_wrapper.unblock();' >close</a>
    <a href='$logout' >FB logout</a>
    
    <div class='console_out'><pre>$out</pre></div>
    ";
    }catch (FacebookApiException $e) {
        
        $message = $e->getMessage();
        $pos = stripos($message,'permission:');
        if($pos){
            $permission = substr($message, $pos + 11);
            $params['scope']=$permission;  
            $loginUrl = $facebook->getLoginUrl($params);  
            $login = "<a href='$loginUrl'>Requires extended permission [$permission] </a>";      
        }

        echo "
            <a href='#' onclick='_wrapper.unblock();' >close</a> <hr>
            $login
            <div>$message</div>
        "; 
        exit;            
    }

}
